package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.workable.model.ActRuTask;
import com.uinnova.product.eam.workable.repository.ActRuTaskRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.api.Task;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 子流程任务挂起监听器，子流程中多个实例驳回审批回将后续审批任务执行完后将任务挂起
 *
 * @author lichong
 * @since 2024/7/22 上午10:34
 */
@Slf4j
@Service("suspensionTaskActiveListener")
public class SuspensionTaskActiveListener implements TaskListener {


    @Resource
    private ActRuTaskRepository actRuTaskRepository;

    @Resource
    private TaskService taskService;

    @Override
    public void notify(DelegateTask delegateTask) {

        String processInstanceId = delegateTask.getProcessInstanceId();
        String assignee = delegateTask.getAssignee();
        List<ActRuTask> actRuTasks = actRuTaskRepository
                .findActRuTaskByAssigneeAndProcInstIdAndSuspensionState(assignee, processInstanceId, SuspensionState.SUSPENDED.getStateCode());
        //激活所有挂起的任务
        if (!CollectionUtils.isEmpty(actRuTasks)) {
            for (ActRuTask actRuTask : actRuTasks) {
                actRuTask.setSuspensionState(SuspensionState.ACTIVE.getStateCode());
            }
            actRuTaskRepository.saveAllAndFlush(actRuTasks);
            //执行审批
            for (ActRuTask task : actRuTasks) {
                taskService.complete(task.getId());
            }
        }
    }
}
